import router from './router';
import store from './store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getToken } from '@/utils/auth';
import getPageTitle from '@/utils/get-page-title';

NProgress.configure({ showSpinner: false });

const whiteList = ['/login'];

router.beforeEach((to, from, next) => {
	debugger;
	NProgress.start();

	document.title = getPageTitle(to.meta.title);

	const hasToken = getToken();
	console.info(hasToken);
	if (hasToken) {
		if (to.path === '/login') {
			next({ path: '/' });
		} else {
			if (!store.state.user.currentUser || !store.state.user.currentUser.id) {
				store.dispatch('user/getPermissionsByToken');
			}
			next();
		}
	} else {
		if (whiteList.indexOf(to.path) !== -1) {
			next();
		} else {
			next(`/login?redirect=${to.path}`);
		}
	}
});

router.afterEach(() => {
	NProgress.done();
});
